"""
语音合成引擎基类
定义所有语音合成引擎的通用接口
"""

from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Union, Any
from dataclasses import dataclass
from enum import Enum


class AudioFormat(Enum):
    """支持的音频格式"""
    WAV = "wav"
    MP3 = "mp3"
    OGG = "ogg"
    FLAC = "flac"


@dataclass
class VoiceProfile:
    """语音配置文件"""
    id: str
    name: str
    language: str
    gender: str  # male, female, neutral
    age: Optional[str] = None
    accent: Optional[str] = None
    engine: str = "pyttsx3"
    settings: Optional[Dict[str, Any]] = None


@dataclass
class TTSRequest:
    """语音合成请求"""
    text: str
    voice_profile: Optional[VoiceProfile] = None
    rate: int = 200  # 语速
    volume: float = 0.9  # 音量 0.0-1.0
    pitch: int = 50  # 音调
    format: AudioFormat = AudioFormat.WAV
    sample_rate: int = 22050
    output_path: Optional[str] = None


@dataclass
class TTSResponse:
    """语音合成响应"""
    success: bool
    audio_data: Optional[bytes] = None
    audio_path: Optional[str] = None
    duration: Optional[float] = None
    error_message: Optional[str] = None
    metadata: Optional[Dict[str, Any]] = None


class TTSEngine(ABC):
    """语音合成引擎抽象基类"""
    
    def __init__(self, config: Optional[Dict[str, Any]] = None):
        self.config = config or {}
        self._engine = None
        self._available_voices: List[VoiceProfile] = []
    
    @abstractmethod
    async def initialize(self) -> bool:
        """初始化语音合成引擎"""
        pass
    
    @abstractmethod
    async def synthesize(self, request: TTSRequest) -> TTSResponse:
        """语音合成"""
        pass
    
    @abstractmethod
    async def get_available_voices(self) -> List[VoiceProfile]:
        """获取可用的语音列表"""
        pass
    
    @abstractmethod
    async def set_voice_profile(self, voice_profile: VoiceProfile) -> bool:
        """设置语音配置"""
        pass
    
    @abstractmethod
    async def cleanup(self):
        """清理资源"""
        pass
    
    @property
    def engine_name(self) -> str:
        """引擎名称"""
        return self.__class__.__name__
    
    @property
    def is_initialized(self) -> bool:
        """是否已初始化"""
        return self._engine is not None
    
    def validate_request(self, request: TTSRequest) -> bool:
        """验证请求参数"""
        if not request.text or not request.text.strip():
            return False
        
        if not (0.0 <= request.volume <= 1.0):
            return False
        
        if request.rate < 50 or request.rate > 500:
            return False
        
        return True
    
    def create_error_response(self, error_message: str) -> TTSResponse:
        """创建错误响应"""
        return TTSResponse(
            success=False,
            error_message=error_message
        )


class TTSException(Exception):
    """语音合成异常"""
    pass


class VoiceNotFoundError(TTSException):
    """语音未找到异常"""
    pass


class SynthesisError(TTSException):
    """合成失败异常"""
    pass


class UnsupportedFormatError(TTSException):
    """不支持的格式异常"""
    pass
